﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using Ninject;
using PetaPoco;
using Meraz.Core.Model;

namespace Meraz.Core.Parsers
{
    public interface IFacebookBoardParser
    {
        FacebookTopicBoard ParseBoard(FileInfo file);
        FacebookTopicBoard ParseBoard(string content);
        void ParseTopic(string content, FacebookTopic topic);
        void ParsePost(string content, FacebookTopicPost post);
    }
    public class FacebookBoardParser : IFacebookBoardParser
    {
        public FacebookBoardParser() { }

        static Regex TOPICS_REGEX = new Regex(@"<a.+?href=""(?<Url>.+?uid=(?<BoardIDStr>\d+?)&(?:amp;)?topic=(?<IDStr>\d+?))"">\s*(?<Title>.+?)\s*</a></h2>[^>]+\>(?<TotalString>\d+) post.+?data-date=""(?<CreatedDateString>[^""]+)""");
        static Regex POST_REGEX = new Regex(@"id=""post(?<IDStr>\d+?)"">.+?actorDescription"".+?>(?<Poster>.+?)</div>\s*<span class=""messageBody"".+?>(?<Text>.+?)</span><?/h6>.+?<abbr.+?data-date=""(?<CreatedDateString>.+?)""");
        static Regex POST_DELETED_REGEX = new Regex(@"(?<Text>Post Deleted)</h6>.+?<abbr.+?data-date=""(?<CreatedDateString>.+?)""");
        static Regex TOPIC_TOTAL_REGEX = new Regex(@"<div class=""summary"">.+?\s(?<TotalString>\d+)\spost");
        
        public FacebookTopicBoard ParseBoard(FileInfo file)
        {

            FacebookTopicBoard board = ParseBoard(File.ReadAllText(file.FullName));
            foreach (FacebookTopic topic in board.Topics)
            {
                topic.Url = topic.Url.Replace("&amp;", "&");
                topic.BoardID = board.ID;
                topic.Status = StatusType.New.ToString();
            }
            return board;
        }

        public FacebookTopicBoard ParseBoard(string content)
        {
            FacebookTopicBoard result = new FacebookTopicBoard();
            try
            {
                long uid = 0;
                string uidStr = RegexFacebookParser.GetUID(content);
                long.TryParse(uidStr, out uid);
                result.ID = uid;
                result.Name = RegexFacebookParser.GetTitle(content);
                result.Topics = RegexFacebookParser.GetObjects<FacebookTopic>(content, TOPICS_REGEX);
            }
            catch (Exception ex)
            {

                Debug.WriteLine(ex);
            }
            return result;
        }

        public void ParseTopic(string content, FacebookTopic topic)
        {
            topic.TotalString = RegexFacebookParser.GetString(content, TOPIC_TOTAL_REGEX, "TotalString");
            int start = content.IndexOf(@"<div class=""DiscussionThread"">") - 1;
            if (start < 0) return;
            int end = content.IndexOf(@"<div class=""pagerpro_container"">", start);
            if (end < 0)
                end = content.IndexOf(@"<div id=""editor""", start);
            if (end < 0)
                end = content.IndexOf(@"<div id=""pageFooter"">");
            if (end < start)
                content = content.Substring(start);
            else
                content = content.Substring(start, end - start);
            int deletedID = 0;
            foreach (String item in Regex.Split(content, @"<li class=""\w\w\w\s"))
            {
                FacebookTopicPost post;
                post = RegexFacebookParser.GetObject<FacebookTopicPost>(item, POST_REGEX);
                if (string.IsNullOrWhiteSpace(post.Text))
                {
                    post = RegexFacebookParser.GetObject<FacebookTopicPost>(item, POST_DELETED_REGEX);
                    if (string.IsNullOrWhiteSpace(post.Text))
                        continue;
                    post.Poster = "";
                    post.ID = ++deletedID;
                    post.BoardID = topic.BoardID;
                    post.TopicID = topic.ID;
                }
                else
                {
                    post.Poster = RegexFacebookParser.RemoveHtml(post.Poster);
                    post.BoardID = topic.BoardID;
                    post.TopicID = topic.ID;
                    ParsePost(item, post);
                }
                topic.Posts.Add(post);
            }
            topic.UniqueUsers = topic.Posts.Select(sel => sel.Poster).Distinct().Count();
        }
        public void ParsePost(string content, FacebookTopicPost post)
        {
            if (post.Links == null)
                post.Links = new List<FacebookTopicPostLink>();
            int id = 0;
            int index = 0;
            foreach (string url in RegexFacebookParser.GetLinks(content))
            {
                FacebookTopicPostLink link = new FacebookTopicPostLink();
                link.ID = ++id;
                link.PostID = post.ID;
                link.TopicID = post.TopicID;
                link.BoardID = post.BoardID;
                link.Status = StatusType.New.ToString();
                link.Url = url.Replace("&amp;", "&");
                link.Text = link.Url;
                link.Index = content.IndexOf(url, index);
                index = (link.Index < 0) ? 0 : link.Index;
                post.Links.Add(link);
            }
        }
    }
}
